package com.zg.paging3.activity.net.adapter

import android.content.Context
import android.text.Html
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.zg.ktcomwan.model.ArticleBean
import com.zg.paging3.R
import com.zg.paging3.databinding.RvItemBinding

/***
 * @Author:      zxd
 * @CreateDate:  2021/7/9 8:19
 * @Description: 为了将 RecyclerView 与 PagingData 联系起来，您需要实现一个 PagingDataAdapter。
 * adpater 构造必须传参数 DiffUtil.ItemCallback，
 * 对DiffUtil.ItemCallback和AsyncListDiffer不了解的可以参考一下这篇文章：Android RecyclerView的正确打开方式——DiffUtil、AsyncListDiff以及最新ListAdapter使用
 * https://blog.csdn.net/weixin_42046829/article/details/110130977
 */
class NetDataAdapter(private val context: Context) :
    PagingDataAdapter<ArticleBean, NetDataAdapter.ViewHolder>(ArticleDiffCallback()) {

    class ViewHolder(val binding: RvItemBinding) : RecyclerView.ViewHolder(binding.root) {

        fun bindData(item: ArticleBean?) {
            binding.tv.text = Html.fromHtml(item?.title) ?: "你猜你猜"
        }
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bindData(getItem(position))
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        /* val binding = DataBindingUtil.inflate<RvItemBinding>(
             LayoutInflater.from(parent.context),
             viewType,
             parent,
             false
         )*/
        val binding = DataBindingUtil.inflate<RvItemBinding>(
            LayoutInflater.from(parent.context),
            R.layout.rv_item,
            parent,
            false
        )
        return ViewHolder(binding)
    }
}

class ArticleDiffCallback : DiffUtil.ItemCallback<ArticleBean>() {
    override fun areItemsTheSame(oldItem: ArticleBean, newItem: ArticleBean): Boolean {
        return oldItem.id == newItem.id
    }

    override fun areContentsTheSame(oldItem: ArticleBean, newItem: ArticleBean): Boolean {
        return oldItem == newItem
    }
}